<template>
  <view class="container">
    <view class="container_header">
      <view slot="right-icon" class="pet_image" @click="getImg(Pet.imgArr,'touxiang')">
        <image v-if="Pet.imgArr.length == 0" src="http://qichong-1256206693-1256206693.cos.ap-nanjing.myqcloud.com/upload/20210617/a1b0aedabc466612a506a75eda513e72.png" mode="widthFix"></image>
        <block v-if="Pet.imgArr.length != 0" v-for="(item,i) in Pet.imgArr" :key="i">
          <image :src="item.link" mode="aspectFill"></image>
        </block>
      </view>
      <van-field :model:value="Pet.nickname" maxlength="10" placeholder-style="text-align:center" input-align="center"
        placeholder="昵称不得超过十个字符" @blur="Blurnickname" />
      <image v-if="Pet.imgArr.length === 0" src="/static/images/mine/update.png" mode="aspectFill" class="minImage">
    </view>

    <van-cell :border="false" title="宠物性别">
      <view class="container_radio">
        <view :class="['container_radio_GG', GenderShow? '' : 'container_radio_active']" @click="RadioGG">
          GG
        </view>
        <view :class="['container_radio_GG', GenderShow? 'container_radio_active' : '']" @click="RadioMM">
          MM
        </view>
      </view>
    </van-cell>

    <van-cell is-link :border="false" title="宠物品种" :value="Pet.varieties" @click="navTo('/subpkg/category/category')">
    </van-cell>

    <van-cell-group :border="false">
      <van-field :border="false" :model:value="Pet.coat" label="宠物毛色" placeholder="请输入毛色" input-align="right"
        @blur="Changecoat"></van-field>
    </van-cell-group>

    <van-cell :border="false" title="绝育情况">
      <view class="container_radio">
        <view :class="['container_radio_GG', CannotShow? '' : 'container_radio_active']" @click="CannotYue">
          是
        </view>
        <view :class="['container_radio_GG', CannotShow? 'container_radio_active' : '']" @click="CannotNo">
          否
        </view>
      </view>
    </van-cell>

    <van-cell :border="false" title="出生日期" is-link :value="Pet.time | dateFormat" @click="Pet_Data" />

    <van-cell :border="false" title="到家日期" is-link :value="Pet.hometime | dateFormat" @click="Home_Pet_Data" />

    <van-cell :border="false" title="添加性格标签（最多选5个）" />
    <van-field :model:value="label" maxlength="5" placeholder-style="font-size:28rpx" placeholder="不超过5个字符"
      @change="Blurlabel">
      <view slot="button" class="Text" @click="addloadlText">添加</view>
    </van-field>

    <view class="container_footer">
      <view class="container_footer_box" v-for="(item,i) in Pet.traitLabelItem" :key="i">
        <text>{{item}}</text>
        <view class="container_footer_box_image" @click="deleteloadlText(i)">
          <image src="/static/images/mine/no.png" mode="aspectFill"></image>
        </view>
      </view>
    </view>

    <van-cell v-if="Pet_id" :border="false" title="专属通证" :value="Pet.token">
    </van-cell>

    <view class="new_pet">
      <button type="success" class="new_pet_button" @click="naw_Petbottom">{{Pet_id?'修改宠物档案':'建立宠物档案'}}</button>
    </view>


    <!-- 时间弹出 -->
    <van-popup :show="Datashow" round position="bottom" custom-style="height: 44%;">
      <van-datetime-picker type="date" :value="currentDate" :max-date="maxDate" @cancel="Pet_CancelData"
        @confirm="Pet_ConfirmData" :formatter="formatter" />
    </van-popup>

    <!-- 时间弹出 -->
    <van-popup :show="HomeDatashow" round position="bottom" custom-style="height: 44%;">
      <van-datetime-picker type="date" :value="currentDate" :max-date="maxDate" @cancel="Home_Pet_CancelData"
        @confirm="Home_Pet_ConfirmData" :formatter="formatter" />
    </van-popup>
  </view>
</template>

<script>
  import {
    removeFile,
  } from "@/api/user.js";

  import {
    storePethealthItem
  } from "@/api/home.js";

  import {
    newchives,
    removelabel
  } from '@/api/new_pet.js'

  import {
    mapGetters,
    mapActions
  } from 'vuex'
  export default {
    data() {
      return {
        Pet: {
          imgArr: [],
          nickname: '',
          coat: '',
          // 时间
          time: '2021-01-01',
          hometime: '2021-01-01',
          // 标签数据
          traitLabelItem: [],
          gender: '0',
          sterilization: '0',
          id: false,
          // 专属通证
          token: false,
          // 品种
          varieties: '请选择'
        },
        // 品种id
        varietiesValue: 0,
        // 富品种id
        varietiesValueId: 0,
        // updateList: [],
        label: '',
        Datashow: false,
        HomeDatashow: false,
        Pet_id: false,
        // 判断是否添加类名
        GenderShow: false,
        // 判断是否绝育
        CannotShow: false,
        currentDate: new Date().getTime(),
        maxDate: new Date().getTime(),
        formatter(type, value) {
          if (type === 'year') {
            return `${value}年`;
          } else if (type === 'month') {
            return `${value}月`;
          }
          return value;
        },
      };
    },
    computed: {
      ...mapGetters('m_user', ['currentStoreId']),
      ...mapGetters('m_pet', ['RecordCategoryId'])
    },
    onLoad(option) {
      this.Pet_id = option.id
      if (this.Pet_id) {
        // 获取回显修改
        this.updateTypeItem()
      }
    },
    filters: {
      //过滤器 用于格式化时间
      dateFormat: function(value) {
        var date = new Date(value); //时间戳为10位需*1000，时间戳为13位的话不需乘1000
        var year = date.getFullYear();
        var month = ("0" + (date.getMonth() + 1)).slice(-2);
        var sdate = ("0" + date.getDate()).slice(-2);
        // 拼接
        var result = year + "-" + month + "-" + sdate
        // 返回
        return result;
      },
    },
    methods: {
      ...mapActions('m_pet', ['AddCategoryList']),
      // 回显修改
      updateTypeItem() {
        storePethealthItem(this.Pet_id).then(res => {
          // console.log(res)
          this.Pet.nickname = res.data.productName
          this.Pet.imgArr = res.data.previewImage !== '' ? this.imgArrArr(res.data.previewImage.split(',')) : []
          this.Pet.time = res.data.birthday
          this.Pet.gender = res.data.sex
          if (res.data.sex === '0') {
            this.GenderShow = false
          } else {
            this.GenderShow = true
          }
          this.Pet.hometime = res.data.arriveHomeDate
          this.Pet.coat = res.data.coatColor
          this.Pet.sterilization = res.data.neuter
          if (res.data.neuter === '0') {
            this.CannotShow = false
          } else {
            this.CannotShow = true
          }
          this.Pet.traitLabelItem = res.data.labels.split(',')
          this.Pet.id = res.data.id
          this.Pet.token = res.data.token
          this.Pet.varieties = res.data.categoryName
          this.varietiesValue = res.data.categoryId
          this.varietiesValueId = res.data.categoryParentId
        })
      },
      Blurnickname(e) {
        // console.log(e)
        this.Pet.nickname = e.detail.value
      },
      Changecoat(e) {
        // console.log(e)
        this.Pet.coat = e.detail.value
      },
      Pet_Data() {
        this.Datashow = true
      },
      Pet_ConfirmData(e) {
        this.Datashow = false
        // console.log(e.detail)
        this.Pet.time = e.detail
      },
      Pet_CancelData() {
        this.Datashow = false
      },
      Home_Pet_Data() {
        this.HomeDatashow = true
      },
      Home_Pet_ConfirmData(e) {
        this.HomeDatashow = false
        // console.log(e.detail)
        this.Pet.hometime = e.detail
      },
      Home_Pet_CancelData() {
        this.HomeDatashow = false
      },
      Blurlabel(e) {
        // console.log(e)
        this.label = e.detail
      },
      // 添加标签
      addloadlText() {
        if (this.label.trim()) {
          this.Pet.traitLabelItem.push(this.label)
          // console.log(this.Pet.traitLabelItem)
          this.label = ''
        } else {
          uni.showToast({
            title: '不能添加特殊字符',
            icon: 'none'
          })
        }
      },
      // 删除标签
      deleteloadlText(i) {
        this.Pet.traitLabelItem.splice(i, 1)
      },
      RadioGG() {
        this.Pet.gender = '0'
        this.GenderShow = false
      },
      RadioMM() {
        this.Pet.gender = '1'
        this.GenderShow = true
      },
      CannotYue() {
        this.Pet.sterilization = '0'
        this.CannotShow = false
      },
      CannotNo() {
        this.Pet.sterilization = '1'
        this.CannotShow = true
      },
      getImg(imageData, type) {
        let self = this;
        self.$util.uploadImageOne('blade-resource/oss/endpoint/put-file', function(res) {
          const data = JSON.parse(res)
          // console.log(data)
          if (imageData.length !== 0) {
            let imgInfo = {
              link: data.data.link,
              name: data.data.name
            }
            self.CloseImage(imageData, 0)
            imageData.push(imgInfo)
            return
          }
          // console.log(data)
          imageData.push(data.data)
        });
      },
      CloseImage(data, i) {
        // console.log(event)
        // console.log(this.Pet.imgArr[i].name.substr(7))
        removeFile(data[i].name).then(res => {
          // console.log(res)
          if (res.code !== 200) return uni.showToast({
            title: "删除失败"
          })
          data.splice(i, 1)
          // console.log(data)
        })
      },
      navTo(url) {
        uni.navigateTo({
          url: url
        })
      },
      async naw_Petbottom() {
        if (this.Pet.nickname == '') {
          return uni.showToast({
            title: '请填写昵称！',
            icon: 'none'
          })
        }
        if (this.Pet.imgArr.length == 0) {
          return uni.showToast({
            title: '请上传头像！',
            icon: 'none'
          })
        }

        const imgArr = []
        this.Pet.imgArr.forEach(item => {
          imgArr.push(item.link)
        })

        if (this.Pet_id) {
          // 修改
          const updateuser = {
            previewImage: imgArr.join(''),
            productName: this.Pet.nickname,
            sex: this.Pet.gender,
            birthday: this.$util.formatDateTime(new Date(this.Pet.time)).substr(0, 10),
            arriveHomeDate: this.$util.formatDateTime(new Date(this.Pet.hometime)).substr(0, 10),
            coatColor: this.Pet.coat,
            neuter: this.Pet.sterilization,
            labels: this.Pet.traitLabelItem.join(','),
            id: this.Pet.id,
            categoryParentId: this.varietiesValueId,
            categoryId: this.varietiesValue
          }
          this.AddCategoryList(updateuser)
        } else {
          // 创建
          // console.log(this.Pet.traitLabelItem.join(','))
          if (this.Pet.time <= this.Pet.hometime) {
            const user = {
              previewImage: imgArr.join(''),
              productName: this.Pet.nickname,
              sex: this.Pet.gender,
              birthday: this.$util.formatDateTime(new Date(this.Pet.time)).substr(0, 10),
              arriveHomeDate: this.$util.formatDateTime(new Date(this.Pet.hometime)).substr(0, 10),
              coatColor: this.Pet.coat,
              neuter: this.Pet.sterilization,
              labels: this.Pet.traitLabelItem.join(','),
              categoryParentId: this.varietiesValueId,
              categoryId: this.varietiesValue
            }
            this.AddCategoryList(user)
          } else {
            uni.showToast({
              title: '出生日期必须小于到家日期哦 ~',
              icon: 'none'
            })
          }
        }
      },
      // 优化 从后台回显的图片数据
      imgArrArr(num) {
        const img = []
        num.forEach(item => {
          img.push({
            link: item,
            name: item.substr(50)
          })
        })
        return img
      }
    }
  }
</script>

<style lang="scss">
  /deep/ .van-picker {
    padding: 24rpx;
    font-size: 36rpx;

    .van-picker__cancel,
    .van-picker__confirm {
      color: rgba(61, 61, 61, 1);
      font-size: 34rpx;
    }

    .van-ellipsis {
      font-size: 32rpx;
    }
  }

  /deep/ .van-popup {
    overflow: hidden;
  }

  /deep/ .van-cell {
    padding-top: 35rpx !important;
    padding-bottom: 35rpx !important;
    align-items: center;
    width: 100% !important;

    .van-cell__title {
      font-size: 28rpx !important;
      line-height: 64rpx;
    }
  }

  /deep/ .Text {
    color: #000000;
    font-size: 30rpx;
  }

  .container {
    padding-bottom: 220rpx;

    .container_header {
      position: relative;
      padding-top: 46rpx;
      width: 100%;
      height: 331rpx;
      // background-color: #f9f9f9;
      text-align: center;
      display: flex;
      flex-direction: column;
      align-items: center;
      justify-content: center;

      .pet_image {
        position: relative;
        width: 170rpx;
        height: 170rpx;
        // margin-bottom: 10rpx;
        // overflow: hidden;
        display: flex;
        justify-content: center;

        image {
          width: 100%;
          height: 100%;
          border-radius: 50%;
        }
      }

      .minImage {
        position: absolute;
        bottom: 127rpx;
        // left: 0;
        width: 38rpx;
        height: 38rpx;
      }
    }

    .container_radio {
      display: flex;
      justify-content: flex-end;

      .container_radio_GG {
        width: 100rpx;
        height: 54rpx;
        background-color: rgba(61, 61, 61, 0.1);
        border-radius: 211rpx;
        text-align: center;
        line-height: 54rpx;
        margin-left: 22rpx;
        color: rgba(61, 61, 61, 0.5);
        font-size: 30rpx;
      }

      .container_radio_active {
        color: #000;
        background-color: rgba(253, 211, 56, 1);
      }
    }

    .container_footer {
      display: flex;
      // width: 100%;s
      // height: 100rpx;
      flex-wrap: wrap;
      // background-color: #07C160;
      padding: 30rpx 48rpx;

      .container_footer_box {
        position: relative;
        margin-right: 30rpx;
        margin-bottom: 30rpx;

        text {
          padding: 12rpx 40rpx;
          background-color: #FDD338;
          border-radius: 211rpx;
          font-size: 26rpx;
        }

        .container_footer_box_image {
          position: absolute;
          right: -12rpx;
          top: -6rpx;
          width: 38rpx;
          height: 38rpx;
          overflow: hidden;
          border-radius: 50%;


          image {
            width: 100%;
            height: 100%;
          }
        }
      }
    }

    .new_pet {
      position: fixed;
      z-index: 99;
      bottom: 0;
      padding: 24rpx;
      width: 750rpx;
      height: 128rpx;
      box-sizing: border-box;
      background-color: #fff;

      .new_pet_button {
        width: 702rpx;
        height: 82rpx;
        background-color: #FDD338;
        border-radius: 6px;
        color: rgba(61, 61, 61, 1);
        line-height: 82rpx;
        border-radius: 82rpx;
        font-size: 16px;
        font-weight: 500;
      }
    }
  }
</style>
